# -*- coding: utf-8 -*-

from contextvars import ContextVar
from starlette.types import ASGIApp, Receive, Scope, Send

from wintersweet.utils.base import Utils
from wintersweet.utils.structure import ContextPrintType, EmptyStrPrintType


REQUEST_ID_CONTEXT = ContextVar('_request_id', default=EmptyStrPrintType())
request_id_context_type = ContextPrintType(REQUEST_ID_CONTEXT)


class RequestIDMiddleware:

    @staticmethod
    def get_request_id():

        return REQUEST_ID_CONTEXT.get()

    def __init__(self, app: ASGIApp) -> None:

        self._app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:

        if scope.get('method'):
            REQUEST_ID_CONTEXT.set(Utils.uuid.uuid1().hex)

        await self._app(scope, receive, send)
